package com.competition.commgr.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import com.competition.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.competition.commgr.mapper.TeamMapper;
import com.competition.commgr.domain.Team;
import com.competition.commgr.service.ITeamService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.Authentication;



/**
 * 团队Service业务层处理
 */
@Service
public class TeamServiceImpl implements ITeamService
{
    @Autowired
    private TeamMapper teamMapper;

    /**
     * 查询团队
     *
     * @param teamId 团队主键
     * @return 团队
     */
    @Override
    public Team selectTeamByTeamId(Long teamId)
    {
        return teamMapper.selectTeamByTeamId(teamId);
    }

    /**
     * 查询团队列表
     *
     * @param team 团队
     * @return 团队集合
     */
    @Override
    public List<Team> selectTeamList(Team team)
    {
        List<Team> teamList = teamMapper.selectTeamList(team);
        // 为每个团队加载成员信息
        for (Team t : teamList) {
            t.setMembers(teamMapper.selectTeamMembers(t.getTeamId()));
        }
        return teamList;
    }

    /**
     * 新增团队
     *
     * @param team 团队
     * @return 结果
     */
    @Override
    public int insertTeam(Team team)
    {
        return teamMapper.insertTeam(team);
    }

    /**
     * 修改团队
     *
     * @param team 团队
     * @return 结果
     */
    @Override
    public int updateTeam(Team team)
    {
        return teamMapper.updateTeam(team);
    }

    /**
     * 批量删除团队
     *
     * @param teamIds 需要删除的团队主键集合
     * @return 结果
     */
    @Override
    public int deleteTeamByTeamIds(Long[] teamIds)
    {
        return teamMapper.deleteTeamByTeamIds(teamIds);
    }

    /**
     * 删除团队信息
     *
     * @param teamId 团队主键
     * @return 结果
     */
    @Override
    public int deleteTeamByTeamId(Long teamId)
    {
        return teamMapper.deleteTeamByTeamId(teamId);
    }

    /**
     * 查询团队成员列表
     */
    @Override
    public List<Team.TeamMember> selectTeamMembers(Long teamId) {
        return teamMapper.selectTeamMembers(teamId);
    }

    /**
     * 添加团队成员
     */
    @Override
    public int insertTeamMember(Long teamId, Long userId, Long teamType) {
        // 检查成员是否已存在
        int count = teamMapper.checkMemberExists(teamId, userId);
        if (count > 0) {
            throw new RuntimeException("该成员已在此团队中");
        }
        return teamMapper.insertTeamMember(teamId, userId, teamType);
    }

    /**
     * 修改团队成员信息
     */
    @Override
    public int updateTeamMember(Map<String, Object> params) {
        // 参数验证
        if (params.get("membersId") == null) {
            throw new RuntimeException("成员ID不能为空");
        }
        return teamMapper.updateTeamMember(params);
    }

    /**
     * 删除团队成员
     */
    @Override
    public int deleteTeamMember(Long membersId) {
        return teamMapper.deleteTeamMember(membersId);
    }

    /**
     * 查询团队奖金信息
     * 通过查询表award这个团队是否获奖，获奖了根据查询获奖记录表award里的level获奖等级和查询赛项表competitions，
     * 查询赛项类别competitions_type和赛事级别competitions_grade,再去根据查询的数据
     * (level(获奖等级),competitions_type(赛项类别),competitions_grade(赛项级别))去查询指导团队和参赛团队的奖金金额，
     * 没有获奖分配的奖金金额为0
     */
    @Override
    public Map<String, Object> selectTeamBonusInfo(Long teamId) {
        Map<String, Object> bonusInfo = teamMapper.selectTeamBonusInfo(teamId);

        // 如果没有查询到数据，返回默认值
        if (bonusInfo == null || bonusInfo.isEmpty()) {
            bonusInfo = new HashMap<>();
            bonusInfo.put("teamId", teamId);
            bonusInfo.put("teamName", "");
            bonusInfo.put("competitionName", "");
            bonusInfo.put("comItemName", "");
            bonusInfo.put("awardStatus", "未获奖");
            bonusInfo.put("awardLevel", "");
            bonusInfo.put("competitionType", "");
            bonusInfo.put("competitionGrade", "");
            bonusInfo.put("instructorBonus", 0);
            bonusInfo.put("participantBonus", 0);
            bonusInfo.put("totalBonus", 0);
        }

        return bonusInfo;
    }

    /**
     * 获取可用用户列表（用于添加团队成员）
     */
    @Override
    public List<Map<String, Object>> selectAvailableUsers() {
        return teamMapper.selectAvailableUsers();
    }

    /**
     * 调试用户团队数据
     */
    @Override
    public List<Map<String, Object>> debugUserTeamsDetail(Long userId) {
        return teamMapper.debugUserTeamsDetail(userId);
    }

    /**
     * 检查所有用户团队
     */
    @Override
    public Map<String, Object> checkAllUserTeams(Long userId) {
        Map<String, Object> result = new HashMap<>();

        // 获取所有团队调试信息
        List<Map<String, Object>> debugInfo = teamMapper.debugUserTeamsDetail(userId);
        result.put("debugInfo", debugInfo);

        // 统计信息
        int totalTeams = debugInfo.stream()
                .map(info -> info.get("team_id"))
                .distinct()
                .toArray().length;
        result.put("totalTeams", totalTeams);

        // 获取有效团队（通过审核的）
        List<Map<String, Object>> validTeams = teamMapper.selectAvailableUsers();
        result.put("validTeams", validTeams);
        result.put("validTeamCount", validTeams.size());

        return result;
    }

    // ============== 奖金分配相关方法实现 ==============

    /**
     * 查询团队可分配奖金信息
     */
    @Override
    public Map<String, Object> selectDistributableBonusInfo(Long teamId) {
        if (teamId == null) {
            throw new RuntimeException("团队ID不能为空");
        }

        List<Map<String, Object>> bonusInfoList = teamMapper.selectDistributableBonusInfo(teamId);
        if (bonusInfoList == null || bonusInfoList.isEmpty()) {
            // 返回默认的空奖金信息
            Map<String, Object> defaultInfo = new HashMap<>();
            defaultInfo.put("teamId", teamId);
            defaultInfo.put("teamName", "");
            defaultInfo.put("competitionName", "");
            defaultInfo.put("comItemName", "");
            defaultInfo.put("awardStatus", "未获奖");
            defaultInfo.put("awardLevel", "");
            defaultInfo.put("competitionType", "");
            defaultInfo.put("competitionGrade", "");
            defaultInfo.put("instructorBonus", 0);
            defaultInfo.put("participantBonus", 0);
            defaultInfo.put("totalBonus", 0);
            return defaultInfo;
        }

        return bonusInfoList.get(0);
    }

    /**
     * 执行奖金分配
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> executeBonusDistribution(Long teamId, Integer instructorBonus, Integer participantBonus) {
        try {
            // 1. 参数验证
            validateBonusDistributionParams(teamId, instructorBonus, participantBonus);

            // 2. 检查团队是否存在
            Team team = teamMapper.selectTeamByTeamId(teamId);
            if (team == null) {
                throw new RuntimeException("团队不存在");
            }

            // 3. 检查团队是否有获奖记录
            if (!checkTeamHasAward(teamId)) {
                throw new RuntimeException("该团队没有获奖记录，无法分配奖金");
            }

            // 4. 检查团队成员是否存在
            List<Team.TeamMember> members = teamMapper.selectTeamMembers(teamId);
            if (members == null || members.isEmpty()) {
                throw new RuntimeException("该团队没有成员，无法分配奖金");
            }

            // 5. 统计各类型人数
            int instructorCount = 0;
            int participantCount = 0;
            for (Team.TeamMember member : members) {
                if (member.getTeamType() == 111L) {
                    instructorCount++;
                } else if (member.getTeamType() == 112L) {
                    participantCount++;
                }
            }

            // 6. 验证奖金分配合理性
            if (instructorCount == 0 && instructorBonus > 0) {
                throw new RuntimeException("没有指导老师，但分配了指导奖金");
            }
            if (participantCount == 0 && participantBonus > 0) {
                throw new RuntimeException("没有参赛学生，但分配了参赛奖金");
            }

            // 7. 执行奖金分配
            int updatedRows = teamMapper.executeBonusDistribution(teamId, instructorBonus, participantBonus);

            if (updatedRows == 0) {
                throw new RuntimeException("奖金分配失败，未更新任何记录");
            }

            // 8. 获取分配结果
            Map<String, Object> result = teamMapper.selectBonusDistributionResult(teamId);
            result.put("updatedRows", updatedRows);
            result.put("distributionTime", new java.util.Date());
            result.put("instructorCount", instructorCount);
            result.put("participantCount", participantCount);
            result.put("instructorPerPerson", instructorCount > 0 ? (double) instructorBonus / instructorCount : 0);
            result.put("participantPerPerson", participantCount > 0 ? (double) participantBonus / participantCount : 0);

            return result;

        } catch (Exception e) {
            throw new RuntimeException("奖金分配失败: " + e.getMessage());
        }
    }

    /**
     * 查询分配后的奖金结果
     */
    @Override
    public Map<String, Object> selectBonusDistributionResult(Long teamId) {
        if (teamId == null) {
            throw new RuntimeException("团队ID不能为空");
        }

        Map<String, Object> result = teamMapper.selectBonusDistributionResult(teamId);
        if (result == null || result.isEmpty()) {
            // 返回默认结果
            result = new HashMap<>();
            result.put("teamId", teamId);
            result.put("teamName", "");
            result.put("memberCount", 0);
            result.put("instructorCount", 0);
            result.put("participantCount", 0);
            result.put("totalInstructorBonus", 0);
            result.put("totalParticipantBonus", 0);
            result.put("totalMoney", 0);
        }

        return result;
    }

    /**
     * 检查团队是否有获奖记录
     */
    @Override
    public boolean checkTeamHasAward(Long teamId) {
        if (teamId == null) {
            return false;
        }
        int awardCount = teamMapper.checkTeamHasAward(teamId);
        return awardCount > 0;
    }

    /**
     * 验证奖金分配参数
     */
    private void validateBonusDistributionParams(Long teamId, Integer instructorBonus, Integer participantBonus) {
        if (teamId == null || teamId <= 0) {
            throw new RuntimeException("团队ID不能为空");
        }
        if (instructorBonus == null || instructorBonus < 0) {
            throw new RuntimeException("指导老师奖金不能为负数");
        }
        if (participantBonus == null || participantBonus < 0) {
            throw new RuntimeException("参赛选手奖金不能为负数");
        }
        if (instructorBonus == 0 && participantBonus == 0) {
            throw new RuntimeException("奖金总额不能为零");
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> resetTeamBonus(Long teamId) {
        try {
            // 验证团队是否存在
            Team team = teamMapper.selectTeamByTeamId(teamId);
            if (team == null) {
                throw new RuntimeException("团队不存在");
            }

            // 执行重置
            int updatedRows = teamMapper.resetTeamBonus(teamId);

            Map<String, Object> result = new HashMap<>();
            result.put("teamId", teamId);
            result.put("teamName", team.getTeamName());
            result.put("updatedRows", updatedRows);
            result.put("resetTime", new Date());
            result.put("message", "奖金重置成功");

            return result;

        } catch (Exception e) {
            throw new RuntimeException("奖金重置失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> resetMemberBonus(Long membersId) {
        try {
            // 执行重置
            int updatedRows = teamMapper.resetMemberBonus(membersId);

            if (updatedRows == 0) {
                throw new RuntimeException("成员不存在");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("membersId", membersId);
            result.put("updatedRows", updatedRows);
            result.put("resetTime", new Date());
            result.put("message", "成员奖金重置成功");

            return result;

        } catch (Exception e) {
            throw new RuntimeException("成员奖金重置失败: " + e.getMessage());
        }
    }


    // 在 TeamServiceImpl.java 中添加
    @Override
    public boolean checkTeamManagementPermission(Long teamId) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = SecurityUtils.getUserId();

            // 检查是否为第一位指导老师
            int count = teamMapper.checkIsFirstInstructor(teamId, currentUserId);
            return count > 0;

        } catch (Exception e) {
            // 如果获取用户信息失败，返回无权限
            return false;
        }
    }

    @Override
    public Map<String, Object> getFirstInstructorInfo(Long teamId) {
        Long firstInstructorId = teamMapper.getFirstInstructorId(teamId);

        Map<String, Object> result = new HashMap<>();
        if (firstInstructorId != null) {
            // 这里可以查询用户详细信息
            result.put("firstInstructorId", firstInstructorId);
            result.put("hasFirstInstructor", true);
        } else {
            result.put("hasFirstInstructor", false);
        }
        return result;
    }
}